﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;

namespace CRM.Database.Model
{
    public class TechnicRequestsCollection : AbstractCollection
    {
        /// <summary>
        /// Стaтическая коллекция 
        /// </summary>
        protected static List<TechnicRequests> _list;

        public List<TechnicRequests> TechnicRequestsList
        {
            get
            {
                return Entities.TechnicRequests.OrderByDescending(p => p.IdTechnicRequest).ToList();
                if (_list == null)
                    _list = DB.Entities.TechnicRequests.ToList();
                return _list;
            }
        }

        /// <summary>
        /// Возвращает запланированные заявки в виде назначений для календаря
        /// </summary>
        /// <returns></returns>
        public List<SchedulerAppointments> RequestsAsSchedulerAppointments
        {
            get
            {
                var result = new List<SchedulerAppointments>();
                foreach (TechnicRequests request in TechnicRequestsList)
                {
                    if (request == null) continue;
                    if (request.IdTechnic <= 0) continue;
                    if (request.PlannedDate == null) continue;
                    var appointment = new SchedulerAppointments();
                    appointment.ResourceID = request.IdTechnic;
                    appointment.EndDate = appointment.StartDate.AddDays(0.5);
                    appointment.Subject = request.LegalEntityName;
                    appointment.Status = 0;
                    appointment.Type = 0;
                    appointment.Label = 1;
                    appointment.AllDay = false;
                    appointment.UniqueID = request.IdTechnicRequest;

                 
                    appointment.StartDate = (DateTime) request.PlannedDate;
                    // appointment.Location = request.City;
                    result.Add(appointment);
                }
                return result;
            }
        }

        /// <summary>
        /// Возвращает техников в виде ресурсов для календаря
        /// </summary>
        /// <returns></returns>
        public List<SchedulerResources> TechnicsAsSchedulerResources
        {
            get
            {

               


                var col = new UsersCollection();
                var result = new List<SchedulerResources>();

                foreach (var technic in col.Technics)
                {
                    if (technic == null) continue;
                    if (!technic.HasTechnicRequest) continue;
                    var resourceItem = new SchedulerResources
                                           {
                                               ResourceID = technic.IdUser,
                                               UniqueID = technic.IdUser,
                                               ResourceName = technic.LocalizedFullName
                                           };
                    result.Add(resourceItem);
                }

                //foreach (var request in TechnicRequestsList)
                //{
                //    if (request == null) continue;
                //    if (request.IdTechnic <= 0) continue;
                //    var user = col.GetUserbyId(request.IdTechnic);
                //    {
                //        if (user != null)
                //        {
                //            var resourceItem = new SchedulerResources
                //                                   {
                //                                       ResourceID = user.IdUser,
                //                                       UniqueID = user.IdUser,
                //                                       ResourceName = user.LocalizedFullName
                //                                   };
                //            result.Add(resourceItem);
                //        }
                //    }
                //}
                return result;
            }
        }

        /// <summary>
        /// Обнуление статической коллекции
        /// </summary>
        protected override void SetStaticListToNULL()
        {
            _list = null;
        }

        /// <summary>
        /// Получение статического списка для хранения объектов
        /// </summary>
        /// <returns></returns>
        public override object GetStaticCollection()
        {
            return _list;
        }

        /// <summary>
        /// Получение элемента из коллекции по идентификатору
        /// </summary>
        /// <param name="itemId">Идентификатор</param>
        /// <returns>Элемент</returns>
        public override object GetItemById(int itemId)
        {
            return Entities.TechnicRequests.Find(itemId);
        }

        /// <summary>
        /// получить список заявок клиента
        /// </summary>
        /// <param name="idCustomer"></param>
        /// <returns></returns>
        public List<TechnicRequests> GetRequestsByCustomerId(int idCustomer)
        {
            var result = new List<TechnicRequests>();
            if (idCustomer < 1) return result;
            if (TechnicRequestsList.Count < 1) return result;
            foreach (TechnicRequests item in TechnicRequestsList)
            {
                if (item.IdCustomer == idCustomer)
                    result.Add(item);
            }
            return result;
        }

        /// <summary>
        /// получить список заявок конкретного техника
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        public List<TechnicRequests> GetRequestsByUser(Users user)
        {
            var result = new List<TechnicRequests>();
            if (user == null) return result;
            if (TechnicRequestsList.Count < 1) return result;
            foreach (TechnicRequests item in TechnicRequestsList)
            {
                if (item.IdTechnic == user.IdUser)
                    result.Add(item);
            }
            return result;
        }

        /// <summary>
        /// Удаление заявки вместе с привязками
        /// </summary>
        /// <param name="item"></param>
        /// <returns></returns>
        public new bool Delete(object item)
        {
            var request = (TechnicRequests) item;
            if (request == null) return false;
            bool result = true;
            //удаление аттачментов
            if (request.TechnicRequestAttachments != null)
            {
                var attachmentsCol = new TechnicRequestAttachmentsCollection();
                List<TechnicRequestAttachments> attachmentsList = request.TechnicRequestAttachments.ToList();
                foreach (TechnicRequestAttachments attachment in attachmentsList)
                {
                    if (attachment == null) continue;
                    //request.TechnicRequestAttachments.Remove(attachment);
                    //Save();
                    Entities.Entry(attachment).State = EntityState.Deleted;
                    Save();
                    //result = attachmentsCol.Delete(attachment);
                }
            }

            //удаление привязок к системам
            if (request.TechnicRequestsProductSystems != null)
            {
                var bindingsCol = new TechnicRequestsProductSystemsCollection();
                List<TechnicRequestsProductSystems> bindingSystemsList = request.TechnicRequestsProductSystems.ToList();
                foreach (TechnicRequestsProductSystems bindingItem in bindingSystemsList)
                {
                    if (bindingItem == null) continue;
                    Entities.Entry(bindingItem).State = EntityState.Deleted;
                    Save();
                    //result = bindingsCol.Delete(bindingItem);
                }
            }

            //удаление привязок типов выездов к заявке
            if (request.TechnicRequestsVisitsTypes != null)
            {
                var bindingsCol1 = new TechnicRequestsVisitsTypesCollection();
                List<TechnicRequestsVisitsTypes> visitsList = request.TechnicRequestsVisitsTypes.ToList();
                foreach (TechnicRequestsVisitsTypes bindingItem1 in visitsList)
                {
                    if (bindingItem1 == null) continue;
                    Entities.Entry(bindingItem1).State = EntityState.Deleted;
                    Save();
                    //result = bindingsCol1.Delete(bindingItem1);
                }
            }

            //удаление привязок оборудования к заявке
            if (request.TechnicRequestsEquipments != null)
            {
                var bindingsCol2 = new TechnicRequestsEquipmentsCollection();
                List<TechnicRequestsEquipments> equipmentsList = request.TechnicRequestsEquipments.ToList();
                foreach (TechnicRequestsEquipments bindingsItem2 in equipmentsList)
                {
                    if (bindingsItem2 == null) continue;
                    Entities.Entry(bindingsItem2).State = EntityState.Deleted;
                    Save();
                    //result = bindingsCol2.Delete(bindingsItem2);
                }
            }

            //удаление отчетов

            //удаление отчета №1
            if (request.TechnicReport1 != null)
            {
                var report1Col = new TechnicReport1Collection();
                List<TechnicReport1> report1List = request.TechnicReport1.ToList();
                foreach (TechnicReport1 report1 in report1List)
                {
                    if (report1 == null) continue;
                    Entities.Entry(report1).State = EntityState.Deleted;
                    Save();
                    //result = report1Col.Delete(report1);
                }
            }

            //удаление отчета №2
            if (request.TechnicReport2 != null)
            {
                var report2Col = new TechnicReport2Collection();
                List<TechnicReport2> report2List = request.TechnicReport2.ToList();
                foreach (TechnicReport2 report2 in report2List)
                {
                    if (report2 == null) continue;
                    Entities.Entry(report2).State = EntityState.Deleted;
                    Save();
                    //result = report2Col.Delete(report2);
                }
            }

            //удаление отчета №3
            if (request.TechnicReport3 != null)
            {
                var report3Col = new TechnicReport3Collection();
                List<TechnicReport3> report3List = request.TechnicReport3.ToList();
                foreach (TechnicReport3 report3 in report3List)
                {
                    if (report3 == null) continue;
                    Entities.Entry(report3).State = EntityState.Deleted;
                    Save();
                    //result = report3Col.Delete(report3);
                }
            }

            //удаление отчета №4
            if (request.TechnicReport4 != null)
            {
                var report4Col = new TechnicReport4Collection();
                List<TechnicReport4> report4List = request.TechnicReport4.ToList();
                foreach (TechnicReport4 report4 in report4List)
                {
                    if (report4 == null) continue;
                    Entities.Entry(report4).State = EntityState.Deleted;
                    Save();
                    //result = report4Col.Delete(report4);
                }
            }

            //удаление отчета №5
            if (request.TechnicReport5 != null)
            {
                var report5Col = new TechnicReport5Collection();
                List<TechnicReport5> report5List = request.TechnicReport5.ToList();
                foreach (TechnicReport5 report5 in report5List)
                {
                    if (report5 == null) continue;
                    Entities.Entry(report5).State = EntityState.Deleted;
                    Save();
                    //result = report5Col.Delete(report5);
                }
            }

            //удаление отчета №6
            if (request.TechnicReport6 != null)
            {
                var report6Col = new TechnicReport6Collection();
                List<TechnicReport6> report6List = request.TechnicReport6.ToList();
                foreach (TechnicReport6 report6 in report6List)
                {
                    if (report6 == null) continue;
                    Entities.Entry(report6).State = EntityState.Deleted;
                    Save();
                    //result = report6Col.Delete(report6);
                }
            }

            //удаление отчета №7
            if (request.TechnicReport7 != null)
            {
                var report7Col = new TechnicReport7Collection();
                List<TechnicReport7> report7List = request.TechnicReport7.ToList();
                foreach (TechnicReport7 report7 in report7List)
                {
                    if (report7 == null) continue;
                    Entities.Entry(report7).State = EntityState.Deleted;
                    Save();
                    //result = report7Col.Delete(report7);
                }
            }

            //удаление отчета №8
            if (request.TechnicReport8 != null)
            {
                var report8Col = new TechnicReport8Collection();
                List<TechnicReport8> report8List = request.TechnicReport8.ToList();
                foreach (TechnicReport8 report8 in report8List)
                {
                    if (report8 == null) continue;
                    Entities.Entry(report8).State = EntityState.Deleted;
                    Save();
                    //result = report8Col.Delete(report8);
                }
            }

            //удаление отчета №9
            if (request.TechnicReport9 != null)
            {
                var report9Col = new TechnicReport9Collection();
                List<TechnicReport9> report9List = request.TechnicReport9.ToList();
                foreach (TechnicReport9 report9 in report9List)
                {
                    if (report9 == null) continue;
                    Entities.Entry(report9).State = EntityState.Deleted;
                    Save();
                    //result = report9Col.Delete(report9);
                }
            }

            //удаление отчета №10
            if (request.TechnicReport10 != null)
            {
                var report10Col = new TechnicReport10Collection();
                List<TechnicReport10> report10List = request.TechnicReport10.ToList();
                foreach (TechnicReport10 report10 in report10List)
                {
                    if (report10 == null) continue;
                    Entities.Entry(report10).State = EntityState.Deleted;
                    Save();
                    //result = report10Col.Delete(report10);
                }
            }

            //удаление отчета №11
            if (request.TechnicReport11 != null)
            {
                var report11Col = new TechnicReport11Collection();
                List<TechnicReport11> report11List = request.TechnicReport11.ToList();
                foreach (TechnicReport11 report11 in report11List)
                {
                    if (report11 == null) continue;
                    Entities.Entry(report11).State = EntityState.Deleted;
                    Save();
                    //result = report11Col.Delete(report11);
                }
            }

            //удаление отчета №12
            if (request.TechnicReport12 != null)
            {
                var report12Col = new TechnicReport12Collection();
                List<TechnicReport12> report12List = request.TechnicReport12.ToList();
                foreach (TechnicReport12 report12 in report12List)
                {
                    if (report12 == null) continue;
                    Entities.Entry(report12).State = EntityState.Deleted;
                    Save();
                    //result = report12Col.Delete(report12);
                }
            }

            //удаление самой заявки
            result = base.Delete(item);
            return result;
        }

        #region Overrides of AbstractCollection

        /// <summary>
        /// Обновление элемента в коллекции
        /// </summary>
        /// <param name="item">Новый элемент</param>
        /// <param name="userLogin">Логин пользователя, который делает изменения</param>
        /// <returns>Результат операции</returns>
        public bool Update(object item, string userLogin)
        {
            var newObject = (TechnicRequests) item;
            if (newObject == null)
                return false;

            var object4Update = GetItemByIdFromDatabase(newObject.GetKeyValue()) as TechnicRequests;
            if (object4Update == null)
                return false;

            if (!string.IsNullOrEmpty(newObject.Comments))
                object4Update.Comments = newObject.Comments;

            if (!string.IsNullOrEmpty(newObject.Report))
                object4Update.Report = newObject.Report;

            object4Update.IdCustomer = newObject.IdCustomer;
            object4Update.IdLegalEntity = newObject.IdLegalEntity;
            object4Update.IdContact = newObject.IdContact;
            object4Update.IdAddress = newObject.IdAddress;
            object4Update.IdTechnicRequestStatus = newObject.IdTechnicRequestStatus;
            object4Update.CreateDate = newObject.CreateDate;
            object4Update.BeginDate = newObject.BeginDate;
            object4Update.EndDate = newObject.EndDate;
            object4Update.PlannedDate = newObject.PlannedDate;
            object4Update.IdTechnic = newObject.IdTechnic;
            object4Update.Duration = newObject.Duration;

            return base.Update(object4Update, userLogin);
        }

        /// <summary>
        /// Получение списка элементов
        /// </summary>
        /// <returns>Список элементов</returns>
        public override List<object> GetList()
        {
            return new List<object>(TechnicRequestsList);
        }

        /// <summary>
        /// Получение типа текущего элемента
        /// </summary>
        /// <returns></returns>
        protected override Type GetItemType()
        {
            return typeof (TechnicRequests);
        }

        #endregion
    }
}